#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/7 14:11
# @Author  : CoderCharm
# @File    : views.py
# @Software: PyCharm
# @Desc    :
"""

"""
from datetime import timedelta
from typing import Any, List, Union

from sqlalchemy.orm import Session
from fastapi import APIRouter, Depends,Query
from api.api_v1.rbacm.schemas import role_schema
from core import security

from api.common import deps
from api.utils import response_code
from api.common.logger import logger

from api.models import auth
from core.config import settings

from .schemas import user_schema, token_schema

from .crud import curd_user, curd_role,curd_resource

router = APIRouter()


#添加角色
@router.post("/add/addrole", summary="添加角色")
async def add_role(
        role_info: role_schema.RoleCreate,
        db: Session = Depends(deps.get_db),
):
    logger.info(f"添加角色->用户id:,角色名:{role_info.name}")
    curd_role.create(db=db, obj_in=role_info)
    return response_code.resp_200(message="分类成功")

#获取角色列表
@router.get('/getrolelist',summary="获取角色列表")
async def getrolelist( db: Session = Depends(deps.get_db),
                page: int = Query(1, ge=1, title="当前页"),
        page_size: int = Query(10, le=50, title="页码长度")
):
    res = curd_role.queryall_role(db,page=page,page_size=page_size)
    return response_code.resp_200(data=res)
    


# #添加资源
# #获取二级资源列表
@router.get("/gettworesource",summary="获取二级资源列表")
async def gettworesource(
    db: Session = Depends(deps.get_db)
):
    res = curd_resource.querytwo_resource(db)
    return response_code.resp_200(data=res)
# #角色配制资源
@router.get("/del_resource",summary="获取二级资源列表")
async def del_resource(
    db: Session = Depends(deps.get_db),
    ids:str=''
):
    print("***")
    print(ids)
    idlist = ids.split(",")
    print(idlist)
    res = curd_resource.del_resource(db,ids=idlist)
    return response_code.resp_200(data={"code":22})

#通过角色id获取对应的资源列表
@router.get("/getRoleResource",summary="通过角色id获取对应的资源列表")
async def getRoleResource(
    db: Session = Depends(deps.get_db),
    roleid:int=0
):
    res = curd_resource.get_roleresource(db,roleid=roleid)
    return response_code.resp_200(data=res)

#通过角色id获取对应的资源列表
@router.post("/setResource",summary="通过角色id设置对应的资源列表")
async def setResource(
    db: Session = Depends(deps.get_db),
    roleid:int=0,
    idlist:str=""
):
    # 调用curd更新资源
    res = curd_resource.setResource(db,roleid=roleid,idlist=idlist)
    print("&&&&")
    print(res)
    if res:
        return response_code.resp_200(data=res)
    else:
        return response_code.resp_1001(data=res,message="资源存在互斥，不能添加")


def  getData(data):
    if len(data)<=0:
        return []
    #定义两个列表
    #一个列表存放pid
    idlist=[]
    #一个列表存放菜单数据 son权限数据
    reslist=[]
    # reslist = [{"id":1,"name":"菜单管理","son":[{"id":1,'name':'用户管理'},{"id":2,'name':'用户22管理'}]}]
    for i in data:
        if i['pid'] not in idlist:
            reslist.append({"id":i['pid'],"name":i['pname'],"son":[{"id":i['id'],'name':i['name'],'url':i['url']}]})
            idlist.append(i['pid'])
        else:
            index = idlist.index(i['pid'])
            reslist[index]['son'].append({"id":i['id'],'name':i['name'],'url':i['url']})

    return reslist

@router.get("/getMenu",summary="通过角色id获取有权限的菜单")
async def getMenu(
     db: Session = Depends(deps.get_db),
     roleid:int=0
):

    res = curd_role.getMenu(db,roleid=roleid)
    data = getData(res)
    return response_code.resp_200(data=data)


